package com.heima.home.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.heima.home.entity.Users;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.secret}") // 从 application.properties 读取密钥
    private String secretKey;

    @Value("${jwt.expiration}") // 从 application.properties 读取过期时间（毫秒）
    private long expiration;

    /**
     * 根据用户信息生成Token
     */
    public String createToken(Users user) {
        Date expireDate = new Date(System.currentTimeMillis() + expiration);
        return JWT.create()
                .withClaim("userId", user.getId())
                .withClaim("userType", user.getUserType())
                .withClaim("username", user.getUsername())
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secretKey));
    }

    /**
     * 校验Token并解析
     */
    public DecodedJWT verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        return verifier.verify(token); // 如果验证失败，这里会抛出异常
    }
}